//
//  BHHomeViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/6/4.
//

import UIKit
import AVFoundation

class BHHomeViewController: BHBaseViewController {

    lazy var homeNavBar: BHHomeNavigationBar = {
        let view = BHHomeNavigationBar.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.begainY)
        view.delegate = self
        return view
    }()
    
    lazy var homeHeaderView: BHHomeHeaderView = {
        let view = BHHomeHeaderView.loadFromXib()
        view.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: BHHomeHeaderView.headerHeight)
        view.delegate = self
        return view
    }()
    
    
    lazy var backScrollView: UIScrollView = {
        let view = UIScrollView.init(frame: CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight-UIScreen.safeBottomHeight-49))
        view.contentSize = CGSize(width: 0, height: UIScreen.showHeight+BHHomeHeaderView.headerHeight-UIScreen.safeBottomHeight-49)
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.delegate = self
        view.rebuild()
        return view
    }()
    
    lazy var childContaintScorllView: UIScrollView = {
        let view = UIScrollView.init(frame: CGRect(x: 0, y: BHHomeHeaderView.headerHeight, width: UIScreen.height, height: UIScreen.showHeight-UIScreen.safeBottomHeight-49-50))
        view.isPagingEnabled = true
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.bounces = false
        view.rebuild()
        view.isScrollEnabled = false
        return view
    }()
    
    lazy var serviceManager: BHHomeServiceManager = {
        let manager = BHHomeServiceManager.init()
        return manager
    }()
    
    
    var canHomeScrollFlag: Bool = true
    fileprivate var childrenVC: BHHomeChildViewController!
    fileprivate var childAppendArray: [BHHomeChildViewController] = []
    fileprivate var current: Int = 0
    
    fileprivate var ifHaveUnRead: Bool = false
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.fixScorll()
        if BHMeUserInfoModel.shared.token.isEmpty == false &&
            self.homeHeaderView.banner.count == 0{
            
            self.serviceManager.homeService()
        }
        
        V2TIMManager.sharedInstance()?.getTotalUnreadMessageCount({ (count) in
            self.homeNavBar.redPoint.isHidden = count == 0
        }, fail: { (code, errorMsg) in
            
        })
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 开始请求定位权限
        BHLocationManager.shared.requestLocation()
        
        self.bh_navigationBar.removeFromSuperview()
        self.homeNavBar.placeAreaBtn.setTitle("\(BHLocationManager.shared.cityName) ", for: .normal)
        self.view.addSubview(self.backScrollView)
        self.backScrollView.addSubview(self.homeHeaderView)
        self.backScrollView.addSubview(self.childContaintScorllView)
        self.view.addSubview(self.homeNavBar)
        self.configChild()
        self.homeHeaderView.pageCycleView.relationScrollView = self.childContaintScorllView
        
        self.observerNet()
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshCity), name: NSNotification.Name.init(String.refreshCityKey), object: nil)
        
        self.backScrollView.addRefresh {
            self.serviceManager.homeService()
            self.childrenVC.begainRefreshToPageOne()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(onRecieveNewMessage(noti:)), name: NSNotification.Name.init(TUIKitNotification_TIMMessageListener), object: nil)
    }
    
    @objc func refreshCity() {
        self.homeNavBar.placeAreaBtn.setTitle("\(BHLocationManager.shared.cityName) ", for: .normal)
    }
    
    
    // MARK: 来消息了
    @objc func onRecieveNewMessage(noti: Notification) {
        let message = noti.object as! V2TIMMessage
        if message.isRead == true {
            return
        }else {
            let vc = BHBaseViewController.currentViewController
            if (vc is BHMessageMainViewController) || (vc is TUIChatController) {
                
            }else {
                self.homeNavBar.redPoint.isHidden = false
            }
        }
        
        //建立的SystemSoundID对象,标准长震动
        let soundID = SystemSoundID(kSystemSoundID_Vibrate)
        //执行震动
        AudioServicesPlaySystemSound(soundID)
        
    }
    
    private func configChild() {
        for i in 0...3 {
            let vc = BHHomeChildViewController.init()
            vc.childType = i
            self.childAppendArray.append(vc)
            vc.view.frame = CGRect(x: CGFloat(i)*UIScreen.width, y: 0, width: UIScreen.width, height: self.childContaintScorllView.bh_height)
            self.childContaintScorllView.addSubview(vc.view)
            if i == 0 {
                self.childrenVC = vc
            }
            vc.callHomeCanScroll = { [weak self] in
                self?.canHomeScrollFlag = true
                self?.callChildReset()
            }
            vc.stopRefreshBlock = { [weak self] in
                self?.backScrollView.endRefresh()
            }
        }
        self.childrenVC.begainRefresh()
        self.childContaintScorllView.contentSize = CGSize(width: UIScreen.width*CGFloat(4), height: 0)
        self.childContaintScorllView.alwaysBounceVertical = false;
    }

    func changeToIndex(_ index: Int) {
        self.current = index
        let canScroll = self.childrenVC.childCanScorll
        self.childrenVC = self.childAppendArray[index]
        self.childrenVC.childCanScorll = canScroll
        self.childContaintScorllView.setContentOffset(CGPoint(x: CGFloat(index)*UIScreen.width, y: 0), animated: false)
        self.childrenVC.begainRefresh()
    }
    
    func callChildReset() {
        for child in self.childAppendArray {
            if child.collectionView.contentOffset.y != 0 {
                child.collectionView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
            }
        }
    }
}



extension BHHomeViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if self.canHomeScrollFlag == false{
            scrollView.contentOffset.y = BHHomeHeaderView.headerHeight-50
        }else {
    
            if scrollView.contentOffset.y >= (BHHomeHeaderView.headerHeight-50) {
                scrollView.contentOffset.y = (BHHomeHeaderView.headerHeight-50)
                self.canHomeScrollFlag = false
                self.childrenVC.childCanScorll = true
            }
        }
    }
    
}
 
extension BHHomeViewController {
    func fixScorll()  {
        self.childContaintScorllView.setContentOffset(CGPoint(x: CGFloat(self.current)*UIScreen.width, y: 0), animated: false)
    }
}

// MARK: - 导航点击
extension BHHomeViewController: BHHomeNavigationBarDelegate {
    func didHomeNavigationBarDidSelect(type: Int) {
        if type == 0 {
            let choseCityVC: BHHomeChoseCityViewController = BHHomeChoseCityViewController.init()
            self.navigationController?.pushViewController(choseCityVC, animated: true)
            choseCityVC.choseCityActBlock = {[weak self] (code, name) in
                self?.homeNavBar.placeAreaBtn.setTitle(name+" ", for: .normal)
            }
        }
        if type == 1 {
            self.homeNavBar.redPoint.isHidden = true
            BHRouter.shared.bh_goMessage()
        }
    }
}



extension BHHomeViewController: BHHomeHeaderViewDelegate {
    func homeSecDidChangeToIndex(index: Int) {
        self.changeToIndex(index)
    }
    
 
    func homeItemGroupDidSelectIndex(index: Int) {
        if index == 0 { // 赛事
            let gameVC = BHCompetitionViewController.init()
            self.navigationController?.pushViewController(gameVC, animated: true)
        }
        if index == 1 { // 场馆
            let placeVC = BHStadiumlistViewController.init()
            self.navigationController?.pushViewController(placeVC, animated: true)
        }
        if index == 2 { //运动
            let sportVC = BHSportMainViewController.init()
            self.navigationController?.pushViewController(sportVC, animated: true)
        }
        if index == 3 { // 趣玩
            let funVC = BHFunlistViewController.init()
            self.navigationController?.pushViewController(funVC, animated: true)
        }
    }
}


// MARK: 网络
extension BHHomeViewController {
    func observerNet() {
        self.serviceManager.responseForBannerBlok = { [weak self] banner in
            self?.homeHeaderView.banner = banner
        }
    }
}

